define(function(require, exports, module) {
    var winURL = require('./appJSON');
    var $api = require('./api');
    module.exports = {
        spUrl: "http://yzdd.mall.api.suanhi.cn", //商城请求地址
        appVersion: '1.5.3', //版本,
        appid: 'wx25c9b901cc38c428',
        Payappid: 'wx25c9b901cc38c428',
        ios_URL: "https://itunes.apple.com/cn/app/%E6%9C%89%E5%BC%A0VIP/id1418989902?mt=8", //苹果
        // 判断是否登陆
        is_login: function() {
          var that = this;
                // ||$api.getStorage("user").data.
            var v = ''
            if ($api.getStorage('user')) {
                console.log('已经有user缓存了');
                console.log(JSON.stringify($api.getStorage('user')));
                if ($api.getStorage('user').data.is_mobile_verified == 0 && $api.getStorage('user').data.wechat_verified == 0) { //既没有绑定微信也没有绑定手机号，账号有问题
                    v = 'unlogin'
                }
            }
            // alert(JSON.stringify($api.getStorage("user")))
            if ($api.getStorage("user") == undefined || $api.getStorage("user").data.nickname == undefined || v == 'unlogin') {

                // alert($api.getStorage("user").data.nickname==undefined)
                // alert($api.getStorage('user').data.is_mobile_verified==0&&$api.getStorage('user').data.wechat_verified==0)
                // jm退出登陆
                $api.clearStorage();
                api.sendEvent({
                    name: 'login__'
                });
                console.log('还没有user缓存');
                console.log(JSON.stringify($api.getStorage('user')));
                api.getPrefs({        
                    key: 'isNeedWelcome'    
                }, function(ret, err) {
                    if (ret.value === '') {
                      that.fnShowWelcome();            
                      api.setPrefs({                
                          key: 'isNeedWelcome',
                          value: true
                      })
                    }else{
                      api.openWin({
                          name: 'WeChat_login',
                          url: 'widget://html/login/WeChat_login.html',
                          allowEdit: true,
                          slidBackEnabled: false,
                          pageParam: {}
                      });
                    }
                })
            }
        },

        fnShowWelcome: function() {  
            console.log('frame');  
            api.openFrame({         
                name: 'first_page',
                url: 'widget://src/Shop/shop_index/first_pages/first_page.html',                   
                bounces: false        

            }, function(ret, err) {        
                var name = ret.name;        
                var index = ret.index;    
            })
        },
        /**
         *
         * 判断是否有相关应用
         */
        appInstalled:function(){
          var bundle = ""
          if (api.systemType == 'ios') {
            bundle = "weixin://dl/stickers"
          } else {
            bundle = "com.tencent.mm"
          }

          var installed = api.appInstalled({
            sync: true,
            appBundle: bundle
          })
          return installed
        },
        //判断版本是否在审核状态
        getIsAuditing: function(cb) {
            this.ajax(
                "http://t.gxmp.henghi.com/uri/Auditing/isAuditing", {
                    data: {
                        values: {
                            "version": this.appVersion,
                            "mask": "none"
                        }
                    },
                    method: 'get',
                    showMask: true
                },
                function(res) {
                    console.log('审核状态:' + JSON.stringify(res));
                    // status :0 在审核  1审核通过
                    res.status = 1

                    cb(res)
                }, 'dd'
            )
        },
        // 微信绑定
        wx_bind: function(unionid, real_openid, cb) {
            console.log('user缓存');
            console.log(JSON.stringify($api.getStorage('user')));
            console.log("------");
            if ($api.getStorage('user')) {
                this.ajax(
                    this.spUrl + "/uri/Shopsetting/bindWechat", {
                        data: {
                            values: {
                                "user_id": $api.getStorage('user').data.out_user_id,
                                "openid": real_openid,
                                'unionid': $api.getStorage('user').data.shop_unionid,
                                'app_unionid': unionid,
                                "phone": $api.getStorage('user').data.mobile
                            }
                        },
                        method: 'get',
                        showMask: true
                    },
                    function(res) {
                        if (res.code == 0) {
                            cb(res)
                        } else {
                            api.toast({
                                msg: res.message,
                                duration: 2000,
                                location: 'middle'
                            });
                        }
                    }
                )
            }
        },
        // 检测是否更新
        checkAppVersion: function(cb) {
            var that = this;
            this.ajax(
                this.spUrl + "/uri/Shopsetting/checkAppVersion", {
                    data: {
                        values: {
                            "app_ver": this.appVersion,
                            "mask": "none",
                            "version": this.appVersion
                        }
                    },
                    method: 'get',
                },
                function(res, err) {
                    if (res) {
                        if (res.code == 0) {
                          // 不需要强制更新
                            cb(false)
                        }else{
                          // 必须强制更新，app出现重大问题
                          cb(true,res.data)
                        }
                    }
                });

        },

        // 打开新页面
        openWin: function(name, pageParam, data) {
            var param = {};
            var _pageData = pageParam || {};
            _pageData.prve = api.winName
            param['url'] = winURL[name]
            param['name'] = name
            param['pageParam'] = _pageData
            for (var i in data) {
                param[i] = data[i]
            }
            api.openWin(param)
        },
        // 加载框
        mask: function(params) {
            // api.showProgress(params);
            api.openFrame({
                name: 'Loading',
                url: 'widget://html/Loading.html',
                rect: {
                    x: 0,
                    y: 0,
                    w: api.winWidth,
                    h: api.winHeight
                },
                pageParam: {
                    name: 'test'
                },
                bounces: false,
                bgColor: 'rgba(0,0,0,0)',
                vScrollBarEnabled: false,
                hScrollBarEnabled: false
            });
        },
        // 清除加载框
        unmask: function() {
            // api.hideProgress();
            $api.setTimeout(function() {
                api.setFrameAttr({
                    name: 'Loading',
                    hidden: true
                });
            }, 500)
        },
        // 预览图片
        photoBrowser: function(list, index) {
            var photoBrowser = api.require('photoBrowser')
            photoBrowser.open({
                images: list,
                bgColor: '#000',
                activeIndex: index
            }, function(ret, err) {
                if (ret.eventType == "click") {
                    photoBrowser.close()
                }
            })
        },
        //批量上传图片
        getPictureS: function(maxlength, leng, Upurl, cb) {
            // maxlength 最大上传图片数量
            // Upurl  上传地址
            // leng   当前图片数量
            var that = this
            api.actionSheet({
                title: '选择上传方式',
                cancelTitle: '取消',
                buttons: ['拍照', '从相册中选']
            }, function(ret, err) {
                if (ret.buttonIndex == 1) {
                    that.PzUp(Upurl, function(res) {
                        cb(res)
                    })
                } else if (ret.buttonIndex == 2) {
                    that.XcupLoad(maxlength, leng, Upurl, function(res) {
                        console.log('getPictureS上传图片：' + JSON.stringify(res));
                        cb(res)
                    })
                }
            })
        },
        // 拍照上传图片
        PzUp: function(Upurl, cb) {

            var that = this
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                mediaValue: 'pic',
                destinationType: 'url',
                allowEdit: true,
                quality: 80,
                targetWidth: 750,
                targetHeight: 750,
                saveToPhotoAlbum: false
            }, function(ret, err) {
                if (ret) {
                    if (ret.data != '') {
                        // that.upload([{
                        //     path: ret.data
                        // }], 0, false, Upurl, function(res) {
                        //     cb([res])
                        //     that.unmask();
                        // })
                        var list = [];
                        list.push(ret.data);

                        that.upload([{
                            path: ret.data
                        }], list.length, 0, false, [], Upurl, function(res) {
                            that.unmask({})
                            console.log('res是什么：' + JSON.stringify(res));
                            cb(res)
                        })

                    }
                }
            });
        },
        XcupLoad: function(maxlength, leng, Upurl, cb) {
            var that = this
            var UIMediaScanner = api.require('UIMediaScanner')
            UIMediaScanner.open({
                type: 'picture',
                column: 4,
                classify: false,
                max: maxlength - leng,
                sort: {
                    key: 'time',
                    order: 'desc'
                },
                texts: {
                    stateText: '已选择*项',
                    cancelText: '取消',
                    finishText: '完成'
                },
                styles: {
                    bg: '#fff',
                    mark: {
                        icon: '',
                        position: 'bottom_left',
                        size: 20
                    },
                    nav: {
                        bg: '#eee',
                        stateColor: '#000',
                        stateSize: 18,
                        cancelBg: 'rgba(0,0,0,0)',
                        cancelColor: '#000',
                        cancelSize: 18,
                        finishBg: 'rgba(0,0,0,0)',
                        finishColor: '#000',
                        finishSize: 18
                    }
                },
                exchange: true,
                rotation: true
            }, function(ret) {
                if (ret.list) {
                    console.log('XcupLoad上传图片：' + JSON.stringify(ret.list));
                    if (ret.list.length > 0) {
                        var lists = []
                        var count = 0; // 执行次数
                        // for (var i = 0; i < ret.list.length; i++) {
                        // (function(num) {
                        that.upload(ret.list, ret.list.length, 0, true, [], Upurl, function(res) {

                                for (var i = 0; i < res.length; i++) {
                                    lists.push(res[i]);
                                }
                                that.unmask({})
                                cb(lists)

                                // count++;
                                //   lists.push(res)
                                //   console.log('i的值：'+JSON.stringify(num));
                                //   console.log('upLoad上传图片：'+JSON.stringify(lists));
                                //   if (count == ret.list.length) {
                                //     that.unmask({})
                                //       cb(lists)
                                //   }
                            })
                            // })(i)
                            // }

                    }
                }
            })
        },
        upload: function(list, length, i, off, emptyArr, Upurl, cb) {
            var that = this,
                imageFilter = api.require('imageFilter'),
                UIMediaScanner = api.require('UIMediaScanner');
            if (list[i].path.substr(list[i].path.length - 4, 4) == '.gif') {
                api.toast({
                    msg: '暂不支持gif格式图片',
                    duration: 2000,
                    location: 'middle'
                })
                return
            } else if (list[i].path.substr(list[i].path.length - 5, 5) == '.jpeg') {
                var filename = that.randomString() + '.jpg';
            } else {
                var filename = that.randomString() + '.' + list[i].path.substr(list[i].path.length - 3, 3);
            }
            console.log(filename);
            if (api.systemType == "ios" && off == true) {
                UIMediaScanner.transPath({
                    path: list[i].path
                }, function(ret, err) {
                    imageFilter.compress({
                        img: ret.path,
                        isClarityimg: false,
                        quality: 0.8,
                        save: {
                            album: false,
                            imgPath: api.cacheDir + '/upload/',
                            imgName: filename
                        }
                    }, function(ret, err) {
                        if (ret.status) {
                            that.ajax(
                                Upurl, {
                                    data: {
                                        values: {
                                            "mask": 'mask',
                                            "unionid": $api.getStorage('shop_unionid')
                                        },
                                        files: {
                                            "file": api.cacheDir + '/upload/' + filename
                                        }
                                    },
                                    method: 'post',
                                    showMask: true
                                },
                                function(res) {
                                    // if (res.code == 0) {
                                    //   console.log("上传之后的图片路径："+res.data)
                                    //   cb(res.data)
                                    // }

                                    emptyArr.push(res.data);

                                    if (i == length - 1) {
                                        console.log("上传之后的图片emptyArr：" + res.data)

                                        cb(emptyArr)
                                    } else {
                                        i++;
                                        that.upload(list, length, i, true, emptyArr, Upurl, cb);
                                    }
                                }
                            )
                        }
                    })
                })
            } else {
                console.log('开始compress！！！！！！！！！！！！！！');
                imageFilter.compress({
                    img: list[i].path,
                    isClarityimg: false,
                    quality: 0.8,
                    save: {
                        album: false,
                        imgPath: api.cacheDir + '/upload/',
                        imgName: filename
                    }
                }, function(ret, err) {
                    if (ret.status) {
                        console.log('compress完毕！！！！！！！！！！！！！' + JSON.stringify(ret));
                        that.ajax(
                            Upurl, {
                                data: {
                                    values: {
                                        "mask": 'mask',
                                        "unionid": $api.getStorage('shop_unionid')
                                    },
                                    files: {
                                        "file": api.cacheDir + '/upload/' + filename
                                    }
                                },
                                method: 'post',
                                showMask: true
                            },
                            function(res) {
                                // if (res.code == 0) {
                                //     cb(res.data)
                                // }

                                emptyArr.push(res.data);

                                if (i == length - 1) {
                                    console.log("上传之后的图片路径：" + res.data)
                                    cb(emptyArr)
                                } else {
                                    i++;
                                    that.upload(list, length, i, true, emptyArr, Upurl, cb);
                                }
                            }
                        )
                    } else {
                        console.log('无法compress！！！！！！！！！！！！！');
                        console.log(JSON.stringify(err));
                    }
                })
            }
        },

        getPictureS2: function(maxlength, leng, Upurl, cb) {
            // maxlength 最大上传图片数量
            // Upurl  上传地址
            // leng   当前图片数量
            var that = this
            api.actionSheet({
                title: '选择上传方式',
                cancelTitle: '取消',
                buttons: ['拍照', '从相册中选']
            }, function(ret, err) {
                if (ret.buttonIndex == 1) {
                    that.PzUp2(Upurl, function(res) {
                        cb(res)
                    })
                } else if (ret.buttonIndex == 2) {
                    that.XcupLoad2(maxlength, leng, Upurl, function(res) {
                        console.log('getPictureS2上传图片：' + JSON.stringify(res));
                        cb(res)
                    })
                }
            })
        },
        // 拍照上传图片
        PzUp2: function(Upurl, cb) {

            var that = this
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                mediaValue: 'pic',
                destinationType: 'url',
                allowEdit: true,
                quality: 80,
                targetWidth: 750,
                targetHeight: 750,
                saveToPhotoAlbum: false
            }, function(ret, err) {
                if (ret) {
                    if (ret.data != '') {
                        console.log('拍照上传的图片：' + JSON.stringify(ret.data));
                        var list = [];
                        list.push(ret.data);
                        cb(list);
                    }
                }
            });
        },
        //--上传本地图片
        XcupLoad2: function(maxlength, leng, Upurl, cb) {
            var that = this
            var UIMediaScanner = api.require('UIMediaScanner')
                // var UIMediaScanner = api.require('UIAlbumBrowser')
            UIMediaScanner.open({
                type: 'picture', //UIAlbumBrowser 是image
                // isOpenPreview: false,  //UIAlbumBrowser 的属性
                column: 4,
                classify: false,
                max: maxlength - leng,
                sort: {
                    key: 'time',
                    order: 'desc'
                },
                texts: { //UIMediaScanner 的属性
                    stateText: '已选择*项',
                    cancelText: '取消',
                    finishText: '完成'
                },
                styles: {
                    bg: '#fff',
                    mark: {
                        icon: '',
                        position: 'bottom_left',
                        size: 20
                    },
                    nav: {
                        bg: '#eee',
                        stateColor: '#000',
                        stateSize: 18,
                        cancelBg: 'rgba(0,0,0,0)',
                        cancelColor: '#000',
                        cancelSize: 18,
                        finishBg: 'rgba(0,0,0,0)',
                        finishColor: '#000',
                        finishSize: 18
                    }
                },
                exchange: true, //UIMediaScanner 的属性
                rotation: true
            }, function(ret) {
                if (ret.list) {
                    console.log('XcupLoad上传图片：' + JSON.stringify(ret.list));
                    if (ret.list.length > 0) {
                        var lists = []
                        var count = 0; // 执行次数
                        console.log(JSON.stringify(ret.list));
                        var list = ret.list;

                        for (var i = 0; i < ret.list.length; i++) {
                            count = count + 1;
                            console.log('count1:' + count);
                            if (list[i].path.substr(list[i].path.length - 4, 4) == '.gif') {
                                api.toast({
                                    msg: '暂不支持gif格式图片',
                                    duration: 2000,
                                    location: 'middle'
                                })
                                return
                            } else if (list[i].path.substr(list[i].path.length - 5, 5) == '.jpeg') {
                                var filename = that.randomString() + '.jpg';
                            } else {
                                var filename = that.randomString() + '.' + list[i].path.substr(list[i].path.length - 3, 3);
                            }

                            var off = true;
                            if (api.systemType == "ios" && off == true) {
                                UIMediaScanner.transPath({
                                    path: list[i].path
                                }, function(ret, err) {
                                    console.log("ios转换后的本地路径：" + JSON.stringify(ret.path));
                                    lists.push(ret.path);
                                    if (count == lists.length) {
                                        console.log(JSON.stringify(lists));
                                        cb(lists)
                                    }
                                })
                            } else {
                                console.log(list[i].size);
                                if (list[i].size > 2048100) {
                                    var big_flag = 1;
                                }
                                lists.push(list[i].path);
                                if (count == ret.list.length) {
                                    if (big_flag == 1) {
                                        alert('上传图片超过2M，会有延迟，请耐心等候...')
                                    }
                                    console.log(JSON.stringify(lists));
                                    cb(lists)
                                }
                            }
                        }
                    }
                }
            });
        },
        //--递归上传图片到服务器
        upload2: function(list, length, i, emptyArr, Upurl, cb) {
            var that = this,
                imageFilter = api.require('imageFilter'),
                UIMediaScanner = api.require('UIMediaScanner');
            if (list[i].substr(list[i].length - 5, 5) == '.jpeg') {
                var filename = that.randomString() + '.jpg';
            } else {
                var filename = that.randomString() + '.' + list[i].substr(list[i].length - 3, 3);
            }

            console.log(filename);
            if (api.systemType == "ios") {
                imageFilter.compress({
                    img: list[i],
                    isClarityimg: false,
                    quality: 0.8,
                    save: {
                        album: false,
                        imgPath: api.cacheDir + '/upload/',
                        imgName: filename
                    }
                }, function(ret, err) {
                    if (ret.status) {
                        that.ajax(
                            Upurl, {
                                data: {
                                    values: {
                                        "mask": 'mask',
                                        "unionid": $api.getStorage('shop_unionid')
                                    },
                                    files: {
                                        "file": api.cacheDir + '/upload/' + filename
                                    }
                                },
                                method: 'post',
                                showMask: true,
                            },
                            function(res) {
                                emptyArr.push(res.data);

                                if (i == length - 1) {
                                    console.log("上传之后的图片路径：" + res.data)
                                    cb(emptyArr)
                                } else {
                                    i++;
                                    that.upload2(list, length, i, emptyArr, Upurl, cb)
                                }
                            }
                        )
                    }
                })

            } else {
                imageFilter.compress({
                    img: list[i],
                    isClarityimg: false,
                    quality: 0.8,
                    save: {
                        album: false,
                        imgPath: api.cacheDir + '/upload/',
                        imgName: filename
                    }
                }, function(ret, err) {
                    if (ret.status) {
                        that.ajax(
                            Upurl, {
                                data: {
                                    values: {
                                        "mask": 'mask',
                                        "unionid": $api.getStorage('shop_unionid')
                                    },
                                    files: {
                                        "file": api.cacheDir + '/upload/' + filename
                                    }
                                },
                                method: 'post',
                                showMask: true,
                                async: false,
                            },
                            function(res) {
                                emptyArr.push(res.data);

                                if (i == length - 1) {
                                    console.log("上传之后的图片路径：" + res.data)
                                    cb(emptyArr)
                                } else {
                                    i++;
                                    that.upload2(list, length, i, emptyArr, Upurl, cb)
                                }
                            }
                        )
                    } else {
                        console.log('无法compress！！！！！！！！！！！！！');
                        console.log(JSON.stringify(err));
                    }
                })
            }
        },

        ready: function(vue) {
            $api.addEvt($api.dom('#btn-back'), 'click', function() {
                api.closeWin();
            });

            api.addEventListener({
                name: "keyback"
            }, function(ret, err) {
                api.closeWin();
            });
            $api.addEvt($api.dom('#btn-back-root'), 'click', function() {
                api.closeToWin({
                    name: 'root'
                });
            });
        },
        // 数据请求
        ajax: function(url, data, callback, dd) {
            var opd, real_openid, appid, token, token_key, that = this;
            if ($api.getStorage('user') != undefined) {
                opd = $api.getStorage('user').data.openid //测试openid
            }
            if ($api.getStorage('real_openid')) {
                real_openid = $api.getStorage('real_openid')
            } else {
                real_openid = ""
            }

            if ($api.getStorage('shop_data')) {
                if ($api.getStorage('shop_data').token) {
                    token = $api.getStorage('shop_data').token;
                }
                if ($api.getStorage('shop_data').token_key) {
                    token_key = $api.getStorage('shop_data').token_key;
                }
            }

            if (data.data.values.appid) {
                appid = data.data.values.appid
            } else {
                appid = that.appid
            }
            if (data.data.values.openid != undefined) {
                opd = data.data.values.openid
            }
            if (data.data.values.unionid == undefined || data.data.values.unionid == '' || data.data.values.unionid == null) {
                data.data.values.unionid = $api.getStorage('shop_unionid');
            }
            data.data.values.openid = opd
                // data.data.values.unionid = $api.getStorage('shop_unionid');
            data.data.values.real_openid = real_openid
            data.data.values.my_openid = opd
            data.data.values.appid = appid
                // if($api.getStorage('token_')){
                //   data.data.values.token = $api.getStorage('token_')
                //   data.data.values.token_key = $api.getStorage('token_key')
                // }
            data.data.values.version = this.appVersion //版本
            data.data.values.token = token
            data.data.values.token_key = token_key
            data.deviceId = api.deviceId
            data.systemType = api.systemType
            if (data.data.values.from != undefined) {
                if (data.data.values.mask == '') {
                    data.data.values.from = 'app'
                }
            } else {
                data.data.values.from = 'app'
            }

            data.url = url
            data.timeout = '240'
            if (data.data.method != undefined) {
                data.method = data.data.method
            }
            data.cache = true
            if (data.data.values.mask != undefined) {
                if (data.data.values.mask == 'none') {
                    this.unmask({});
                } else if (data.data.values.mask == 'mask') {
                    this.mask();
                } else {
                    this.mask();
                }
            } else {
                this.mask();
            }
            var str = data.url + '?'
            for (var i in data['data']['values']) {
                str += i + '=' + data['data']['values'][i] + '&'
            }
            console.log('--------------------------')
            console.log(str)
                // --禁止输入表情
                // var reg = /\ud83d[\udc00-\ude4f\ude80-\udfff]/g;
                // if (reg.test(str)) {
            if (that.isEmojiCharacter(str)) {
                api.toast({
                    msg: '禁止输入表情',
                    duration: 2000,
                    location: 'middle'
                });

                that.unmask({});
                return;
            }
            api.ajax(data, function(ret, err) {
                if (data.data.values.mask != 'mask') {
                    that.unmask({});
                }
                if (ret) {
                    console.log('数据获取成功：')
                    callback(ret)
                    if (ret.code != 0) {
                        if (data.data.values.bs != "") {
                            api.toast({
                                msg: ret.message,
                                duration: 2000,
                                location: 'middle'
                            });
                        }
                    }
                    return
                } else if (err) {
                    console.log('数据获取失败：' + JSON.stringify(err))
                    api.toast({
                        msg: "数据获取失败",
                        duration: 2000,
                        location: 'middle'
                    });
                }
            });
        },
        // 监听返回操作
        BACK: function() {
            /*点击页面上的返回按钮*/
            $api.addEvt($api.dom('#btn-back'), 'click', function() {
                /*如果页面入口是领取红包列表页，重新设置顶部状态栏颜色*/
                if (api.pageParam.entrance != 'receive_list') {
                    // api.setStatusBarStyle({
                    //     style: 'dark',
                    //     color: '#ffdb16'
                    // })
                }
                api.closeWin();
            });

            /*监听安卓手机返回键*/
            api.addEventListener({
                name: 'keyback'
            }, function(ret, err) {
                /*如果页面入口是领取红包列表页，重新设置顶部状态栏颜色*/
                // api.setStatusBarStyle({
                //     style: 'dark',
                //     color: '#ffdb16'
                // })
                api.closeWin();
            })
        },
        // 生成随机字符串
        randomString: function() {
            var len = len || 32,
                　　$chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678',
                /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
                　　maxPos = $chars.length,
                pwd = '';　　
            for (i = 0; i < len; i++) {　　　　
                pwd += $chars.charAt(Math.floor(Math.random() * maxPos));　　
            }　　
            return pwd;
        },
        // 检测是否存在表情
        isEmojiCharacter: function(substring) {
            for (var i = 0; i < substring.length; i++) {
                var hs = substring.charCodeAt(i);
                if (0xd800 <= hs && hs <= 0xdbff) {
                    if (substring.length > 1) {
                        var ls = substring.charCodeAt(i + 1);
                        var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                            return true;
                        }
                    }
                } else if (substring.length > 1) {
                    var ls = substring.charCodeAt(i + 1);
                    if (ls == 0x20e3) {
                        return true;
                    }
                } else {
                    if (0x2100 <= hs && hs <= 0x27ff) {
                        return true;
                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                        return true;
                    } else if (0x2934 <= hs && hs <= 0x2935) {
                        return true;
                    } else if (0x3297 <= hs && hs <= 0x3299) {
                        return true;
                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 ||
                        hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b ||
                        hs == 0x2b50) {
                        return true;
                    }
                }
            }
        },
        //--禁用特殊字符
        hasSpecialChar: function(value, msg, type) {
            if (value != '') {
                if (type == 'id_card') {
                    //--身份证验证
                    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                } else if (type == 'email') {
                    //--邮箱验证
                    var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                } else if (type == 'phone') {
                    //--手机号验证
                    var reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
                } else if (type == 'greaterZeroInteger') {
                    //--正整数验证(大于0)
                    var reg = /^([1-9][0-9]*){1,3}$/;
                } else if (type == 'ZeroInInteger') {
                    //--非负整数验证
                    var reg = /^\d+$/;
                } else if (type == 'LetterAndNumber') {
                    //--英文和数字验证（不包含小数）
                    var reg = /^[A-Za-z0-9]{7,15}$/;
                } else if (type == 'floatNumber') {
                    //--最多有六位小数的正实数验证（包括0）
                    var reg = /^[0-9]+(\.[0-9]{1,6})?$/;
                } else {
                    //--禁止输入特殊符号（不包括空格）
                    var reg = /^[\u4E00-\u9FA5A-Za-z0-9\s+]+$/;
                }

                if (!reg.test(value)) {
                    console.log(value);
                    api.toast({
                        msg: msg,
                        duration: 2000,
                        location: 'middle'
                    });
                    return true;
                }
            }
        },
        // 发起聊天
        yz_chat: function(otherUserInfo) {

          var p1 = {
           uid_head: $api.getStorage("user").data.src,
           name: $api.getStorage("user").data.nickname,
           uid: $api.getStorage("user").data.openid,
          };
          var p2 = {
           uid_head: otherUserInfo.src,
           name: otherUserInfo.nickname,
           uid: otherUserInfo.openid,
          };
            api.openWin({
                name: 'webview',
                url: winURL['webview'],
                reload: true,
                pageParam: {
                    p1: p1, //id
                    p2: p2
                }
            });
            // api.openWin({
            //     name: 'chat_',
            //     url: winURL['chat_'],
            //     reload: true,
            //     pageParam: {
            //         otherId: otherUserInfo.openid, //id
            //         nickname: otherUserInfo.nickname, //昵称
            //         src: otherUserInfo.src, //头像
            //         new_nickname: '', //对象
            //         openid2: otherUserInfo.openid
            //     }
            // });
        },
        //--api.toast提示,默认中间显示
        toast: function(msg, type, time) {
            if (msg == '') {
                return;
            }
            var _type = /^(middle)$|^(top)$|^(bottom)$/.test(type) ? type : 'middle';
            var _time = typeof time == 'number' ? time * 1000 : 2000;
            api.toast({
                msg: msg || '信息提示...',
                duration: _time,
                location: _type
            });
        },
        //--获取当前时间
        getCurentTime: function() {
            var now = new Date();

            var year = now.getFullYear(); //年
            var month = now.getMonth() + 1; //月
            var day = now.getDate(); //日

            var hh = now.getHours(); //时
            var mm = now.getMinutes(); //分

            var clock = year + "-";

            if (month < 10)
                clock += "0";

            clock += month + "-";

            if (day < 10)
                clock += "0";

            clock += day + " ";

            if (hh < 10)
                clock += "0";

            clock += hh + ":";
            if (mm < 10) clock += '0';
            clock += mm;
            return (clock);
        },
        //--打开城市选择
        openCitySelect: function() {
            api.openFrame({
                name: 'goShopPerson',
                url: 'widget://src/Shop/city_select/city_select.html',
                reload: true,
                animation: {
                    type: "movein",
                    subType: "from_bottom",
                    duration: 200
                },
                bgColor: 'rgba(0,0,0,.5)'
            });
        },
        //--获取城市选择
        getCitySelect: function(callback) {
            api.addEventListener({
                name: 'citySelect_'
            }, function(ret, err) {
                callback(ret.value);
            });
        },

        downloadImg: function(url, cb) {
            var timestamp = new Date().getTime();
            console.log(url)
            api.download({
                url: url + '?x-oss-process=image/resize,h_50',
                cache: true,
                savePath: api.cacheDir + '/pyq/' + timestamp + '.png',
                allowResume: true
            }, function(ret, err) {
                if (ret.state == 1) {
                    cb(ret.savePath)
                }
                if (ret.state == 2) {
                    api.toast({
                        msg: ret.msg,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },


        //--去商品详情
        goGoodsDetail: function(goodsid, isGroup) {
            if (goodsid == '' || goodsid == undefined) {
                return;
            }
            var _group = typeof isGroup == 'boolean' ? isGroup : false;
            if (!_group) {
                this.openWin("buyGoods", {
                    goodsId: goodsid
                });
            } else {
                this.openWin("groupBuyDetail", {
                    goodsId: goodsid
                });
            }
        },
        // 下拉加载
        refreshHeaderInfo: function(fn, status) {
          var list = [
            'widget://image/refresh/new1.png',
            'widget://image/refresh/new2.png',
            'widget://image/refresh/new3.png',
            'widget://image/refresh/new4.png',
            'widget://image/refresh/new5.png',
            'widget://image/refresh/new6.png',
            'widget://image/refresh/new7.png',
            'widget://image/refresh/new8.png',
            'widget://image/refresh/new9.png',
            'widget://image/refresh/new10.png',
            'widget://image/refresh/new11.png',
            'widget://image/refresh/new12.png',
            'widget://image/refresh/new13.png',
            'widget://image/refresh/new14.png',
            'widget://image/refresh/new15.png',
            'widget://image/refresh/new16.png',
            'widget://image/refresh/new17.png',
            'widget://image/refresh/new18.png',
            'widget://image/refresh/new19.png',
            'widget://image/refresh/new20.png',
            'widget://image/refresh/new21.png',
            'widget://image/refresh/new22.png',
            'widget://image/refresh/new23.png',
            'widget://image/refresh/new24.png',
            'widget://image/refresh/new25.png'
            ]
            api.setCustomRefreshHeaderInfo({
                bgColor: '#FFFFFF',
                images: list
            }, function() {
                fn();
                $api.setTimeout(function() {
                    api.refreshHeaderLoadDone()
                }, 500)
            });
        },
        //--确认订单
        goOrderSure: function(pageData) {
            api.openFrame({
                name: 'buyOrder',
                url: winURL['buyOrder'],
                pageParam: pageData
            });
        },
        //获取用户信息
        getUserInfo: function(openid, callback) {
            this.ajax(
                this.spUrl + "/uri/Shopsetting/getUserInfo", {
                    data: {
                        values: {
                            "openid": openid,
                            "login": 0
                        }
                    },
                    method: 'get',
                    showMask: true
                },
                function(res) {
                    $api.setStorage("user", res)
                    callback(res)
                }
            )
        },
        checkWXLogin: function(dialog) {
          var that = this;
          weiXin = api.require('wx');
          console.log('checkWXLogin的函数');
          console.log(JSON.stringify($api.getStorage('user').data));
           if ($api.getStorage('user')) {
               if (($api.getStorage('user').data.wechat_verified == 0) && ($api.getStorage('Vstatus') == 1)) {
                 dialog.alert({
                   title: '微信授权检测',
                   msg: '请使用微信授权，以方便获取相应用户信息',
                   buttons: ['取消', '确定']
                 }, function(ret) {
                   if(ret.buttonIndex == 2){ //确认
                     weiXin.auth(function(ret, err) {
                         if (ret.status) {
                             // 获取到token  ret.token
                             // 获取授权用户openid
                             weiXin.getToken({
                                 code: ret.code
                             }, function(ret, err) {
                                 if (ret.status) {
                                     weiXin.getUserInfo({
                                         accessToken: ret.accessToken,
                                         openId: ret.openId
                                     }, function(ret, err) {
                                       if (ret.status) {
                                         $api.setStorage('real_openid', ret.openid);
                                         that.wx_bind(ret.unionid, ret.openid, function(res) {
                                             api.toast({
                                                 msg: '绑定成功',
                                                 duration: 2000,
                                                 location: 'middle'
                                             });
                                            //  that.getUserInfo($api.getStorage('user').data.openid, function(res) {
                                             //
                                            //  })
                                         })

                                       } else {
                                           api.toast({
                                               msg: 'user绑定失败' + err.code,
                                               duration: 2000,
                                               location: 'middle'
                                           });
                                       }
                                     });
                                 }
                             });
                         } else {
                             api.toast({
                                 msg: '登陆失败',
                                 duration: 2000,
                                 location: 'middle'
                             });
                         }
                     });
                   }
                 })
               }
           }
       },
    };
})
